package com.zty.config;

import org.apache.http.client.HttpClient;
import org.apache.http.client.config.RequestConfig;
import org.apache.http.config.Registry;
import org.apache.http.config.RegistryBuilder;
import org.apache.http.conn.socket.ConnectionSocketFactory;
import org.apache.http.conn.socket.PlainConnectionSocketFactory;
import org.apache.http.conn.ssl.SSLConnectionSocketFactory;
import org.apache.http.impl.client.HttpClientBuilder;
import org.apache.http.impl.conn.PoolingHttpClientConnectionManager;
import org.springframework.context.annotation.Bean;
import org.springframework.context.annotation.Configuration;
import org.springframework.http.client.ClientHttpRequestFactory;
import org.springframework.http.client.HttpComponentsClientHttpRequestFactory;
import org.springframework.http.client.SimpleClientHttpRequestFactory;
import org.springframework.web.client.RestTemplate;

/**
 * @author ZTY
 * @describe http连接池配置
 * @time 2024-01-22 10:49
 * @projectName zty-short-url
 */
@Configuration
public class RestTemplateConfig {
    @Bean
    public RestTemplate restTemplate(ClientHttpRequestFactory requestFactory){
        return new RestTemplate(requestFactory);
    }

    @Bean
    public ClientHttpRequestFactory httpRequestFactory(){
        SimpleClientHttpRequestFactory factory = new SimpleClientHttpRequestFactory();
        return new HttpComponentsClientHttpRequestFactory(httpClient());
    }

    public HttpClient httpClient(){

        Registry<ConnectionSocketFactory> registry =
                RegistryBuilder.<ConnectionSocketFactory>create()
                        .register("http",
                                PlainConnectionSocketFactory.getSocketFactory())
                        .register("https",
                                SSLConnectionSocketFactory.getSocketFactory())
                        .build();

        PoolingHttpClientConnectionManager connectionManager = new PoolingHttpClientConnectionManager(registry);

        //  设置最大并发数为500
        connectionManager.setMaxTotal(500);

        //  每个域名最大的并发是300，但是所有域名的并发数之和不能超过500
        connectionManager.setDefaultMaxPerRoute(300);

        RequestConfig requestConfig =
                RequestConfig.custom()
                        //返回数据的超时时间
                        .setSocketTimeout(20000)
                        //连接上服务器的超时时间
                        .setConnectTimeout(10000)
                        //从连接池中获取连接的超时时间
                        .setConnectionRequestTimeout(1000)
                        .build();

        return HttpClientBuilder.create()
                .setDefaultRequestConfig(requestConfig)
                .setConnectionManager(connectionManager)
                .build();
    }
}
